/*
Source : https://leetcode.com/problems/swap-nodes-in-pairs/
Author : nflush@outlook.com
Date   : 2016-08-23
*/

/*
24. Swap Nodes in Pairs

    Total Accepted: 115095
    Total Submissions: 317725
    Difficulty: Easy

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Subscribe to see which companies asked this question
*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution { // 4ms
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode node(0);
        ListNode *pre = &node;
        ListNode *cur = head;
        node.next = head;
        while(cur && cur->next){
            cur = cur->next;
            pre->next->next = cur->next;
            cur->next = pre->next;
            pre->next = cur;
            cur = cur->next->next;
            pre = pre->next->next;
        }
        return node.next;
    }
};
class Solution { // 4ms
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode node(0);
        ListNode *pre = &node;
        ListNode *cur = head;
        node.next = head;
        while(cur && cur->next){
            ListNode *next = cur->next;
            cur->next = next->next;
            next->next = cur;
            pre->next = next;

            pre = cur;
            cur = cur->next;
        }
        return node.next;
    }
};

